import { ModalType } from './../plugin/modal.d';
import * as ImageConversion from 'image-conversion'
import { compressAccuratelyConfig, ICompressConfig } from 'image-conversion';
import Modal from "./../plugin/modal"
import { v4 as uuidV4 } from 'uuid';
import { SelfPromise } from '@/common/GlobalType';

const Utils = {
    /**
     * Promise 转 First-Error 格式
     * @param promise
     * @returns
     */
    async to(promise: Promise<any>): SelfPromise {
        try {
            const res = await promise
            return [undefined, res]
        } catch (err) {
            return [err, undefined]
        }
    },

    /**
     * 保存本地
     * @param key
     * @param value
     */
    saveLocal(key: string, value: any): void {
        try {
            localStorage.setItem(key, JSON.stringify(value));
        } catch (e) {
            console.error(e);
        }
    },

    /**
     * 获取本地数据
     * @param key
     * @returns
     */
    getLocal(key: string): string | any {
        const result = localStorage.getItem(key) || "";
        try {
            return JSON.parse(result)
        } catch (e) {
            return result;
        }
    },

    Modal: (): ModalType => Modal as ModalType,

    /**
     * file 文件转 base64 字符串
     * @param file
     * @returns
     */
    FileToBase64: (file: File): SelfPromise => new Promise(async (resolve) => {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
            // base64
            resolve([undefined, reader.result])
        }
        reader.onerror = function (err) {
            resolve([err, undefined])
        }
    }),

    async ImageCompressToFixedSize(file: File, size: compressAccuratelyConfig | number, showModal: boolean = true) {
        const [err, res] = await this.to(ImageConversion.compressAccurately(file, size))
        if (err && showModal) {
            console.log('图片压缩 :>> ', JSON.stringify(err));
            (Modal as ModalType).alert('图片压缩失败~')
        }
        return [err, res]
    },

    async ImageCompressToRatio(file: File, ratio: ICompressConfig | number, showModal: boolean = true) {
        const [err, res] = await this.to(ImageConversion.compress(file, ratio))
        if (err && showModal) {
            console.log('图片压缩 :>> ', JSON.stringify(err));
            (Modal as ModalType).alert('图片压缩失败~')
        }
        return [err, res]
    },

    downLoadImage(file: { url: string, name: string }) {
        const image = new Image();
        // 解决跨域 Canvas 污染问题
        image.setAttribute("crossOrigin", "anonymous");
        image.src = file.url;
        image.onload = () => {
            const canvas = document.createElement("canvas");
            canvas.width = image.width;
            canvas.height = image.height;
            const context = canvas.getContext("2d") as any;
            context.drawImage(image, 0, 0, image.width, image.height);
            canvas.toBlob((blob) => {
                const url = URL.createObjectURL(blob as Blob);
                const a = document.createElement("a");
                a.download = file.name || "photo";
                a.href = url;
                a.click();
                a.remove();
                URL.revokeObjectURL(url);
            });
        };
    },

    /**
     * @description: 生成 [n,m] 的随机整数
     * @param {*} Min
     * @param {*} Max
     * @return {*}
     */
    randomNum(Min: number, Max: number): number {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * Min + 1 + '', 10);
            case 2:
                return parseInt(Math.random() * (Max - Min + 1) + Min + '', 10);
            default:
                return 0;
        }
    },

    loginOut(): void {
        localStorage.removeItem(Constant.LOGIN_TOKEN_KEY)
    },

    isPhone(phoneNumber: string): boolean {
        return (/^1[3456789]\d{9}$/.test(phoneNumber))
    },

    /**
     * 处理数组
     * Example 提取值: [{name:'A'},{name:'B'}] => ['A','B']
     * Example 重构属性: [{name:'A', key:'1'},{name:'B', key:'2'}] => [{value:'A'},{value:'B'}]
     *
     * @param {any[]} source 元数据
     * @param {string} sourceKey 目标字段名
     * @param {string=''} targetKey 存储字段名
     * @returns {string[]|Object[]}
     */
    getArrayByKey: (source: any[] = [], sourceKey: string = "", targetKey: string = ""): string[] => {
        if (targetKey) {
            return source.reduce((result, _) => result.push({ [targetKey]: _[sourceKey] }) && result, [])
        } else {
            return source.reduce((result, _) => result.push(_[sourceKey]) && result, [])
        }
    },

    guid: (): string => {
        const guidWithHyphens = uuidV4(uuidV4()); // 生成带连字符的 GUID
        const guidWithoutHyphens = guidWithHyphens.replace(/-/g, ''); // 去除连字符
        return guidWithoutHyphens;
    },
}
export default Utils

